package org.example.fboot.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.SecureDigestAlgorithm;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * JSON Web Token 工具类
 * @author LiuChuanWei
 * @date 2019-12-11
 */
@Slf4j
public final class JwtUtils {

    private final static SecureDigestAlgorithm<SecretKey, SecretKey> ALGORITHM = Jwts.SIG.HS256;
    /**
     * 私钥
     */
    public static String SECRET_KEY = "0123456789_0123456789_0123456789";

    public static SecretKey KEY = null;
    /**
     * 过期时间（秒单位）
     */
    public static long TOKEN_EXPIRE_MILLIS = 5*60;

    private final static String JWT_ISS = "feng";
    private final static String SUBJECT = "subject";
    /**
     * 创建token
     * @param payloads 用户公共消息
     * @return
     */
    public static String getAccessToken(Map<String, ?> payloads) {
        return Jwts.builder()
                .header().add("typ", "JWT").add("alg", "HS256").and()
                .id(UUID.randomUUID().toString())
                .expiration(Date.from(Instant.now().plusSeconds(TOKEN_EXPIRE_MILLIS)))
                .issuedAt(new Date())
                .subject(SUBJECT)
                .issuer(JWT_ISS)
                .signWith(KEY,ALGORITHM)
                .claims(payloads)
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Jws<Claims> parseClaim(String token){
        return Jwts.parser().verifyWith(KEY).build().parseSignedClaims(token);
    }

    /**
     * 获取头部消息
     * @param token
     * @return
     */
    public static JwsHeader parseHeader(String token){
        return parseClaim(token).getHeader();
    }
    public static Claims parsePayload(String token){
        return parseClaim(token).getPayload();
    }


    public static void main(String[] args) {
//        Map<String, String> map = new HashMap<>();
//        String accessToken = JwtUtils.getAccessToken(map);
//        System.out.println(accessToken);
        Jws<Claims> claim = JwtUtils.parseClaim("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJjZjQ5NDA0NS03MzJmLTQzZWYtYmFhNS0zMjBhYWMyZDAxM2MiLCJleHAiOjE3MTYzOTQxMjAsImlhdCI6MTcxNjM5NDExOCwic3ViIjoic3ViamVjdCIsImlzcyI6ImZlbmcifQ.VrUlSmswrvFlmn58a9kXJNZ5bU8Qh8lU2DRyBz-5pg4");
        System.out.println();
    }
}